package de.pixel83.piecemaster.ai;

import java.util.HashMap;

/**
 * Contains weighting values for a GeneticAi.
 * 
 * @author pixel
 * 
 */
public class DNA {

	private HashMap<String, Integer> map = new HashMap<String, Integer>();

	private DNA() {
		// Only used by recombine()
	}

	public DNA(int pawn, int knight, int bishop, int rook, int queen,
			int king) {
		map.put("pawn", pawn);
		map.put("knight", knight);
		map.put("bishop", bishop);
		map.put("rook", rook);
		map.put("queen", queen);
		map.put("king", king);
	}

	public DNA(String text) {
		String[] arr = text.split(";");
		for (int i = 0; i < arr.length; i++) {
			String[] kvp = arr[i].split("=");
			map.put(kvp[0], Integer.parseInt(kvp[1]));
		}
	}

	/**
	 * Creates a "child" DNA from itself and the given DNA. Attributes are
	 * picked from a random parent.
	 * 
	 * @param mate
	 * @return
	 */
	public DNA recombine(DNA mate) {
		DNA child = new DNA();
		for (String key : map.keySet()) {
			double rand = Math.random();
			Integer value = (Math.round(rand) >= 1 ? map.get(key) : mate
					.get(key));
			child.set(key, value);
		}
		return mate;
	}

	/**
	 * Mutates all attribute values +/- n (or less) percent; mutate(20) on 100
	 * will result in a value of 80-120.
	 * 
	 * @param maxPercent
	 *            Max modification percentage (up/down)
	 */
	public void mutate(int maxPercent) {
		for (String key : map.keySet()) {
			double rand = Math.random();
			int oldValue = map.get(key);
			int maxAbsolute = maxPercent * oldValue / 100;
			int newValue = oldValue - maxAbsolute
					+ (int) Math.round(rand * maxAbsolute * 2);
			map.put(key, newValue);
		}
	}

	public String toString() {
		String text = "";
		boolean isFirst = true;
		for (String key : map.keySet()) {
			if (isFirst) {
				isFirst = false;
			} else {
				text += ";";
			}
			text += key + "=" + map.get(key);
		}
		return text;
	}

	public void set(String key, Integer value) {
		map.put(key, value);
	}

	public Integer get(String key) {
		return map.get(key);
	}
}
